﻿using CoreShop.App.Properties;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WebKit.DOM;

namespace CoreShop.App.Controls
{
    public partial class frmFoodListAI : UIForm
    {
        private int mFoodPageIndex = 0;
        private int mFoodPageSize = 10;
        private int mFoodRowCount = 0;
        private bool sAI_ConnStatus = false;//AI连接状态
        private bool bGetGoodsFlag = true;
        List<corecmsfood> gsAIDataList = new List<corecmsfood>();
        public LxxMatchingResultModel lxxMatchingResult = null;
        private long pdtSpuSpecId = 0;
        public decimal sAI_WeighQty = 0;//AI识别数量
        static System.Timers.Timer timer_focus = null;

        /// <summary>
        /// 总页数
        /// </summary>
        int productPageIndex = 0;

        /// <summary>
        /// 当前选择的页
        /// </summary>
        int selectPageIndex = 0;

        /// <summary>
        /// 每页显示的条数
        /// </summary>
        int PageCountProduct = 10;

        //public static string url = "http://127.0.0.1:17339";
        public frmFoodListAI()
        {
            InitializeComponent();
            Thread.Sleep(StartAiLoad());
            GetConnectState();
            GetRegister();
            CreateFoodList();
            SkinUtil.TraverseControls(this); //更换主题颜色
            txtSearch.TextBox.GotFocus += txtSendKey_GotFocus;
            swtSaveImg.Active = AppConstVars.systemsetup.paraPartialModel.foodImgAutoSave;
            if (timer_focus == null)
            {
                timer_focus = new System.Timers.Timer();//2025-09-09新增
                timer_focus.Interval = 200;
                timer_focus.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
                timer_focus.Enabled = true;
            }
        }

        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    if ((this.Visible) && (!this.txtSearch.Focused))
                    {
                        this.txtSearch.Focus();
                    }
                }));                
            }
            catch { }
        }

        public void SetFormSkin()
        {
            this.PalTop.BackColor = SkinUtil.panelBackColor;
            this.PalTop.FillColor = SkinUtil.panelFillColor;            
        }

        #region 商品按钮加载

        /// <summary>
        /// 菜品按钮名称
        /// </summary>
        /// <param name="deskId"></param>
        /// <returns></returns>
        private string GetFoodItemName(int index)
        {
            return "uiFoodItem_" + index.ToString();
        }

        /// <summary>
        /// 建空的单个菜品按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreateFoodListBtn(int index)
        {
            DishItemInfo dish = new DishItemInfo();
            dish.Name = "";
            dish.Price = "";
            var item = new UIDishItemXp(dish);
            item.Name = GetFoodItemName(index);
            item.Visible = false;
            item.Margin = new System.Windows.Forms.Padding(3);
            item.Tag = "";
            item.Click += Item_Click;
            fly_foodlist.Add(item);
        }
                
        public void SaveGoodsImg(UIDishItemXp item)
        {
            try
            {
                string fileName = item.Info.FoodId.ToString() + ".jpg";
                string path = System.Windows.Forms.Application.StartupPath + "\\LocaleImg";
                string filePath =  path + "\\" + fileName;

                if (picGoods.Image != null)
                {
                    if (File.Exists(filePath)) File.Delete(filePath);
                    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                    Image sourceImage = picGoods.Image;
                    Bitmap bmp = new Bitmap(sourceImage, new Size(200, 200));
                    FoodImgService.SaveAsJPEG(bmp, filePath, 100);
                    item.Image = bmp;
                    (this.Owner as FOrdering).BindFoodImage(item.Info.FoodId);
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
            finally
            {
                GC.Collect();
            }
        }

        /// <summary>
        /// 建空的菜品按钮
        /// </summary>
        private void CreateFoodList()
        {
            fly_foodlist.Clear();
            for (int i = 1; i <= mFoodPageSize; i++)
            {
                CreateFoodListBtn(i);
            }
        }

        /// <summary>
        /// 暂不显示所有菜品菜品
        /// </summary>
        private void HiddenFoodList(int starIndex)
        {
            for (int i = starIndex; i <= mFoodPageSize; i++)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(i));
                var item = (UIDishItemXp)mControl;
                if (item != null) item.Visible = false;
            }
        }

        private void SetDishItemImage(UIDishItemXp item, corecmsfood food)
        {
            try
            {
                if (!AppConstVars.systemsetup.showFoodImg) return;
                FoodUtil foodUtil = new FoodUtil();
                string imgFileName = "";
                if (AppConstVars.systemsetup.paraPartialModel.locaImgFirst)
                {
                    string locaFileName = foodUtil.GetProductLocaImageFile(food);//本地图片优先
                    if (File.Exists(locaFileName))
                    {
                        imgFileName = locaFileName;
                        //item.Image = System.Drawing.Image.FromFile(locaFileName);
                        using (Image image = Image.FromFile(locaFileName))
                        {
                            // 使用图片，例如显示到PictureBox
                            item.Image = new Bitmap(image); // 创建副本，避免原始图片被锁定
                        }
                        return;
                    }
                }

                if (string.IsNullOrEmpty(food.image) && string.IsNullOrEmpty(imgFileName))
                {
                    string locaFileName = foodUtil.GetProductLocaImageFile(food);//本地图片
                    if (File.Exists(locaFileName))
                    {
                        //item.Image = System.Drawing.Image.FromFile(locaFileName);
                        using (Image image = Image.FromFile(locaFileName))
                        {
                            // 使用图片，例如显示到PictureBox
                            item.Image = new Bitmap(image); // 创建副本，避免原始图片被锁定
                        }
                    }
                    else
                        item.Image = Resources.NoImage;
                    return;
                }

                string rmoFileName = foodUtil.GetProductImageFile(food.image);//后台图片                    
                if ((rmoFileName != null) && !File.Exists(rmoFileName))
                {
                    item.Image = Resources.NoImage;
                    new FoodUtil().DownloadProductImage(food, rmoFileName);
                }
                else
                    item.Image = System.Drawing.Image.FromFile(rmoFileName);
            }
            catch { }
        }

        private Expressionable<corecmsfoodspec, corecmsfood> GetExpressionable()
        {
            var where = Expressionable.Create<corecmsfoodspec, corecmsfood>();            
            where = where.And((s, f) => f.isDelete == false && f.sellStatus != 0 && s.onLine == true);
            string sName = txtSearch.Text;
            if (!string.IsNullOrEmpty(sName))
                where = where.And((s, f) => f.name.Contains(sName) || f.number.Contains(sName) || s.code.Contains(sName)
                || f.byName.Contains(sName) || f.helpCode.Contains(sName) || f.pinYin.Contains(sName));

            //where = where.And((s, f) => f.stand > 0 || s.weighType == (int)GlobalEnumVars.WeighType.Weigh);
            where = where.And((s, f) => s.weighType == (int)GlobalEnumVars.WeighType.Weigh);
            return where;
        }

        private void BindFoodList()
        {
            if (mFoodPageIndex < 1) mFoodPageIndex = 1;
            int index = 1;
            fly_foodlist.Visible = false;
            this.fly_foodlist.SuspendLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
            foreach (var row in gsAIDataList)
            {
                var mControl = fly_foodlist.Get(GetFoodItemName(index));
                var item = (UIDishItemXp)mControl;
                if (item != null)
                {
                    item.Tag = row.foodSpecId.ToString();
                    item.Visible = true;
                    item.TextName = row.name;
                    var dish = item.Info;
                    dish.FoodId = row.foodId;
                    dish.Name = row.name;
                    dish.Number = row.code;
                    dish.Price = row.posPrice.ToString();
                    dish.Money = row.posPrice.ToString();
                    dish.UnitName = row.foodUnitName;
                    SetDishItemImage(item, row);//加载商品图片        
                    item.Refresh();
                }
                index++;
            }
            HiddenFoodList(index);
            this.fly_foodlist.ResumeLayout();// 添加很多时挂起会更快（不触发界面更改重新绘图事件）
            fly_foodlist.Visible = true;
            fly_foodlist.Refresh();
            //SetFoodListPageState();
        }

        private void SetFoodListPageState()
        {
            if (mFoodRowCount <= mFoodPageSize)
            {
                btnFoodListPre.Enabled = false;
                btnFoodListNext.Enabled = false;
            }
            else if (mFoodPageIndex == 1)
            {
                btnFoodListPre.Enabled = false;
                btnFoodListNext.Enabled = true;
            }
            else if (mFoodPageIndex * mFoodPageSize > mFoodRowCount)
            {
                btnFoodListPre.Enabled = true;
                btnFoodListNext.Enabled = false;
            }
            else
            {
                btnFoodListPre.Enabled = true;
                btnFoodListNext.Enabled = true;
            }
        }

        #endregion

        public void SetFeedback(Int64 pdtSpuSpecId)
        {
            try
            {
                if ((gsAIDataList == null) || (gsAIDataList.Count == 0))
                {
                    //gsAIDataList = new corecmsfoodServices().QueryPageAsync(ref mFoodRowCount, 1, 9999, GetExpressionable());
                    gsAIDataList = new corecmsfoodspecServices().QueryPageAsync(ref mFoodRowCount, 1, 9999, GetExpressionable());
                }
                switch (AppConstVars.systemsetup.aiType)
                {
                    case (int)GlobalEnumVars.AiType.Czl:
                        SetFeedback_Czl(pdtSpuSpecId);
                        break;
                    case (int)GlobalEnumVars.AiType.Lxx:
                        SetFeedback_Lxx(pdtSpuSpecId);
                        break;
                }
            }
            catch (WebException e)
            {

            }
        }

        /// <summary>
        /// 发送AI识别(深圳创智链chuangzhilian)
        /// </summary>
        public void GetCameraImgThread()
        {
            Thread.Sleep(1000);
            GetCameraImg();
        }

        #region 创智链AI接口

        /// <summary>
        /// 学习(深圳创智链chuangzhilian)
        /// </summary>
        public void SetFeedback_Czl(Int64 pdtSpuSpecId)
        {
            try
            {
                string feedback = "";
                string[] displays = { };
                JArray arrays = new JArray();
                foreach (var item in gsAIDataList)
                {
                    string sName = CommFunc.ConvertNullString(item.number) + "," + CommFunc.ConvertNullString(item.name).Replace(",", "");
                    //string sName = CommFunc.ConvertNullString(item.code) + "," + CommFunc.ConvertNullString(item.name).Replace(",", "");
                    arrays.Add(sName);
                    if (pdtSpuSpecId == CommFunc.ConvertToBigInt(item.foodSpecId)) feedback = sName;
                }
                if (string.IsNullOrEmpty(feedback)) return;
                GlobalConstVars.czlAIBusiness.SetFeedback(feedback, displays, arrays);
            }
            catch (WebException e)
            {

            }
        }

        /// <summary>
        /// 检查激活状态
        /// </summary>
        public void GetRegister()
        {
            switch (AppConstVars.systemsetup.aiType)
            {
                case (int)GlobalEnumVars.AiType.Czl:
                    this.label8.Text = GlobalConstVars.czlAIBusiness.GetRegister();
                    break;
                case (int)GlobalEnumVars.AiType.Lxx:
                    var lxxDeviceInfo = GlobalConstVars.lxxAIBusiness.GetDeviceInfo();
                    if (lxxDeviceInfo == null) return;

                    if ((lxxDeviceInfo != null) && (lxxDeviceInfo.code == 1))
                    {
                        this.Invoke(new Action(() =>
                        {                            
                            this.label8.Text = "已激活";
                        }));
                    }
                    break;
            }                     
        }

        /// <summary>
        /// 发送AI指令(深圳创智链chuangzhilian)
        /// </summary>
        public void GetCameraImg()
        {
            try
            {
                switch (AppConstVars.systemsetup.aiType)
                {
                    case (int)GlobalEnumVars.AiType.Czl:
                        this.Invoke(new Action(() =>
                        {
                            this.picGoods.Image = GlobalConstVars.czlAIBusiness.GetCameraImg(); 
                        }));
                        break;
                    case (int)GlobalEnumVars.AiType.Lxx:
                        this.Invoke(new Action(() =>
                        {
                            this.picGoods.Image = GlobalConstVars.lxxAIBusiness.GetCameraImg();
                        }));
                        break;

                }                              
            }
            catch (Exception ex)
            {
                A_SetLog(" 错误号：Czl_GetCameraImg:" + ex.Message);
            }
        }

        /// <summary>
        /// 发送AI识别(深圳创智链chuangzhilian)
        /// </summary>
        public void GetProducts_Czl(bool logFlag)
        {
            string msg = "";
            List<string> codeList = GlobalConstVars.czlAIBusiness.GetProducts(logFlag, ref msg);
            this.lbl_getmsg.Text = msg;
            if (codeList != null)
            {
                AI_GetDataList(codeList);
                if (this.label8.Text != "已激活") GetRegister();
                this.label4.Text = "已连接";
            }
            (this.Owner as FOrdering).txtInput.HideDropDown();
            this.Show();
            Thread thread = new Thread(GetCameraImgThread);///线程运行
            thread.Start();
        }

        /// <summary>
        /// 创智链AI初始化
        /// </summary>
        public int StartAiLoad()
        {
            if (AppConstVars.systemsetup.aiType == (int)GlobalEnumVars.AiType.None) return 0;
            switch (AppConstVars.systemsetup.aiType)
            {
                case (int)GlobalEnumVars.AiType.Czl:
                    if (GlobalConstVars.czlAIBusiness.ExistsProcess() > 0) return 0;
                    Task.Factory.StartNew(() =>
                    {
                        GlobalConstVars.czlAIBusiness.StartProcess();
                    }).TaskDis();
                    break;
                case (int)GlobalEnumVars.AiType.Lxx:
                    if (GlobalConstVars.lxxAIBusiness == null) GlobalConstVars.lxxAIBusiness = new LxxAIBusiness();
                    if (GlobalConstVars.lxxAIBusiness.ExistsProcess() > 0) return 0;
                    Task.Factory.StartNew(() =>
                    {
                        GlobalConstVars.lxxAIBusiness.StartProcess();
                    }).TaskDis();
                    break;

            }
            return 5000;
        }

        private void GetConnectState()
        {
            bool isConnect = false;
            switch (AppConstVars.systemsetup.aiType)
            {
                case (int)GlobalEnumVars.AiType.Czl:
                    this.label4.Text = GlobalConstVars.czlAIBusiness.GetConnectState(ref isConnect); 
                    break;
                case (int)GlobalEnumVars.AiType.Lxx:
                    this.label4.Text = GlobalConstVars.lxxAIBusiness.GetConnectState(ref isConnect);
                    break;

            }                    
        }

        /// <summary>
        /// 发送AI指令
        /// </summary>
        public void AI_SendMsg(string sCMD, string sDATA1, string sDATA2,bool logFlag = false)
        {
            switch (AppConstVars.systemsetup.aiType)
            {
                case (int)GlobalEnumVars.AiType.Czl:
                    GetProducts_Czl(logFlag); 
                    break;
                case (int)GlobalEnumVars.AiType.Lxx:
                    GetProducts_Lxx(false);
                    break;
            }            
        }

        #endregion

        #region 六小象AI

        public void SetFeedback_Lxx(Int64 pdtSpuSpecId)
        {
            try
            {
                var corecmsfood = gsAIDataList.Find(p => p.foodSpecId == pdtSpuSpecId);
                if (corecmsfood == null) return;
                var learningModel = new LxxLearningModel();
                learningModel.id = lxxMatchingResult.id;
                learningModel.sku.code = corecmsfood.number;
                learningModel.sku.name = corecmsfood.name;
                GlobalConstVars.lxxAIBusiness.SetFeedback(learningModel);
            }
            catch (WebException e)
            {

            }
        }


        /// <summary>
        /// 发送AI识别(深圳创智链chuangzhilian)
        /// </summary>
        public void GetProducts_Lxx(bool logFlag)
        {
            lxxMatchingResult = GlobalConstVars.lxxAIBusiness.GetProducts();
            this.lbl_getmsg.Text = lxxMatchingResult.msg;
            if (lxxMatchingResult == null) return;
            if ((lxxMatchingResult.skuList != null) && (!string.IsNullOrEmpty(lxxMatchingResult.id)))
            {
                List<string> codeList = lxxMatchingResult.skuList.Select(sku => sku.code).ToList();
                AI_GetDataList(codeList);
                if (this.label8.Text != "已激活") GetRegister();
                this.label4.Text = "已连接";
            }
            (this.Owner as FOrdering).txtInput.HideDropDown();
            this.Show();
            Thread thread = new Thread(GetCameraImgThread);///线程运行
            thread.Start();
        }

        #endregion

        private void txtSendKey_GotFocus(object sender, System.EventArgs e)
        { 
            this.txtSearch.Focus();
            keyborad.SetTextBox((UIEdit)sender);
        }

        public void SetTxtKeyClear()
        {
            try
            {
                bGetGoodsFlag = false;
                txtSearch.Text = "";
                bGetGoodsFlag = true;
            }
            catch (Exception ex) { }
        }

        private void Item_Click(object sender, System.EventArgs e)
        {
            UIDishItemXp item = (UIDishItemXp)sender;
            try
            {
                var dish = item.Info;
                pdtSpuSpecId = CommFunc.ConvertToBigInt(item.Tag);
                SetTxtKeyClear();
                //this.sAI_WeighQty = 0;
                this.Hide();
                (this.Owner as FOrdering).AddDataRow(dish.FoodId, pdtSpuSpecId, 1, true);
                SetFeedbackThread(pdtSpuSpecId);
                if (swtSaveImg.Active)
                {
                    SaveGoodsImg(item);
                    swtSaveImg.Active = AppConstVars.systemsetup.paraPartialModel.foodImgAutoSave;
                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message, "错误号：ItemClick"); 
            }
        }

        private void SetFeedbackThread(Int64 pdtSpuSpecId)
        {
            var newThread = new Thread(() => SetFeedback(pdtSpuSpecId), 1024 * 512);
            newThread.IsBackground = true;
            newThread.Start();
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="msg"></param>
        public void A_SetLog(string msg)
        {
            try
            {
                this.rtb_log.Invoke(new Action(() =>
                {
                    if (this.rtb_log.Text.Length > 5000) rtb_log.Text = String.Empty;
                    this.rtb_log.AppendText(msg);
                    this.rtb_log.HideSelection = false;
                }));
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "错误003"); }
        }

        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="codeList"></param>
        private void AI_GetDataList(List<string> codeList)
        {
            try
            {
                var where = Expressionable.Create<corecmsfood, corecmsfoodspec>();
                //where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0 && s.onLine == true);
                where = where.And((f, s) => f.isDelete == false && f.sellStatus != 0);

                if (AppConstVars.systemsetup.paraPartialModel.aiGoodsCodeType == (int)GlobalEnumVars.AiGoodsCodeType.NumberOnly)
                    where = where.And((f, s) => codeList.Contains(s.number));
                else 
                    where = where.And((f, s) => codeList.Contains(s.number) || codeList.Contains(s.code));
                where = where.And((f, s) => s.weighType > 0);
                gsAIDataList = new corecmsfoodServices().QueryPageAsync(ref mFoodRowCount, 1, PageCountProduct, where);                

                selectPageIndex = 1;
                int DataCount = gsAIDataList.Count;
                decimal qty = (decimal)DataCount / (decimal)PageCountProduct;
                productPageIndex = CommFunc.ConvertToInt32(Math.Ceiling(qty));
                BindFoodList();
                this.Show();
            }
            catch (Exception ex)
            {
                //Log.LogManage.Error("czlAi识别错误:" + ex);
            }
        }

        private void AIProductSelect_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.btnClose_Click(null,null);
            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.passphraseInput.Text))
                {
                    MessageBox.Show("激活码不能为空.");
                    return;
                }
                string msg = "";
                bool ret = GlobalConstVars.czlAIBusiness.Register(this.passphraseInput.Text.Trim(), ref msg);
                this.label8.Text = msg;
                if (ret)
                {
                    MessageBox.Show("激活成功，需要重新启动前台系统");
                    Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGetCameraImg_Click(object sender, EventArgs e)
        {
            GetCameraImg();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {            
            selectPageIndex = 1;
            RefrushData(selectPageIndex);
        }

        public void btnFiler_Click(object sender, EventArgs e)
        {
            AI_SendMsg("","","",true);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            (this.Owner as FOrdering).TimerFocusState(true);
            this.sAI_WeighQty = 0;
            this.Hide();
        }

        private void AIProductSelect_Shown(object sender, EventArgs e)
        {
            this.txtSearch.Focus();
            keyborad.SetTextBox((UIEdit)txtSearch.TextBox);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtSearch.Clear();
            txtSearch.Focus();
        }

        private DateTime dLastTime = DateTime.Now;  //定义一个成员函数用于保存每次的时间点,用户判断是扫描还是手工录入
        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (!bGetGoodsFlag) return;
            if (txtSearch.Text.Contains("/") || txtSearch.Text.Contains("\\") || txtSearch.Text.Contains("*"))
            {
                this.txtSearch.TextChanged -= new System.EventHandler(this.txtSearch_TextChanged);
                txtSearch.Text = txtSearch.Text.Replace("/", "").Replace("\\", "").Replace("*", "");
                this.txtSearch.TextChanged += new System.EventHandler(this.txtSearch_TextChanged);
                return;
            }
            DateTime tempDt = DateTime.Now;          //保存按键按下时刻的时间点
            TimeSpan ts = tempDt.Subtract(dLastTime);     //获取时间间隔
            dLastTime = tempDt;
            if (ts.Milliseconds > 150 || !txtSearch.Text.PatternNum())  //判断时间间隔，如果时间间隔大于150毫秒，则将判断为手工输入
            {
                Task.Run(() => ShowData());
            }
        }
  

        private void btnFoodListNext_Click(object sender, EventArgs e)
        {
            //下一页
            if ( selectPageIndex >= productPageIndex) return;
            int PageIndex = ++selectPageIndex;
            RefrushData(PageIndex);
        }

        private void btnFoodListPre_Click(object sender, EventArgs e)
        {
            //上一页
            if (selectPageIndex < 1) return;
            int PageIndex = --selectPageIndex;
            RefrushData(PageIndex);
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) 
            {
                selectPageIndex = 1;
                RefrushData(selectPageIndex);
            }
        }

        public void RefrushData(int PageIndex)
        {
            //gsAIDataList = new corecmsfoodServices().QueryPageAsync(ref mFoodRowCount, PageIndex, PageCountProduct, GetExpressionable());
            gsAIDataList = new corecmsfoodspecServices().QueryPageAsync(ref mFoodRowCount, PageIndex, PageCountProduct, GetExpressionable());
            decimal qty = (decimal)mFoodRowCount / (decimal)PageCountProduct;
            productPageIndex = CommFunc.ConvertToInt32(Math.Ceiling(qty));
            BindFoodList();
        }

        public void ShowData() 
        {
            this.Invoke(new Action(() =>
            {
                string code = txtSearch.Text;
                selectPageIndex = 1;
                RefrushData(selectPageIndex);
            }));
        }

        private void keyborad_OKButtonClick(object sender, string value)
        {
            //查看秤日志口令
            string showlog = "showlog" + System.DateTime.Now.ToString("yyyyMMdd");
            if (value.Equals(showlog, StringComparison.OrdinalIgnoreCase))
            {
                rtb_log.Visible = !rtb_log.Visible;
            }
        }

        private void btnSetLearnDataClear_Click(object sender, EventArgs e)
        {
            switch (AppConstVars.systemsetup.aiType)
            {
                case (int)GlobalEnumVars.AiType.Czl:

                    break;
                case (int)GlobalEnumVars.AiType.Lxx:
                    if (GlobalConstVars.lxxAIBusiness.SetLearnDataClear())
                        ShowInfoTip("清空学习成功。");
                    break;
            }
        }

        private void frmFoodListAI_Load(object sender, EventArgs e)
        {
            if (AppConstVars.mConvert == 1)
                lblScaleTitle.Text = "重量(kg)";
            else
                lblScaleTitle.Text = "重量(斤)";
        }

        private void frmFoodListAI_VisibleChanged(object sender, EventArgs e)
        {
            (this.Owner as FOrdering).TimerFocusState(!this.Visible);//2025-09-09新增
            //this.ShowFullScreen = true;//2025-09-09新增
        }
    }
}